package com.copro.chemdb;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//import org.apache.commons.logging.Log;
//import org.apache.commons.logging.LogFactory;

import com.copro.chemdb.beans.Account;
import com.copro.chemdb.utils.Constants;
import com.copro.simple.SimpleSession;

public class AccessFilter implements Filter {
	// private static final Log log = LogFactory.getLog(AccessFilter.class);

	private boolean adminCheck = false;

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		boolean isPass = false;
		if (SimpleSession.me((HttpServletRequest) request).isLogin()) {
			if (adminCheck) {
				Account account = (Account) ((HttpServletRequest) request)
						.getSession().getAttribute(Constants.USER);
				if (account.getRole() == Account.ADMIN) {
					isPass = true;
				}
			} else {
				isPass = true;
			}
		}

		if (isPass) {
			chain.doFilter(request, response);
		} else {
			// log.warn("NO RIGHT!");
			// save the current url
			HttpSession session = ((HttpServletRequest) request).getSession();
			session.setAttribute(Constants.STOREDURL,
					((HttpServletRequest) request).getRequestURL().toString());
			// go to login page
			((HttpServletResponse) response)
					.sendRedirect(((HttpServletRequest) request)
							.getContextPath()
							+ "/login.jsp");
		}

	}

	@Override
	public void init(FilterConfig conf) throws ServletException {
		String admin = conf.getInitParameter("admin");
		try {
			if (null != admin) {
				adminCheck = Boolean.parseBoolean(admin);
			}
		} catch (Exception e) {
			// do nothiing
		}
	}

}
